let traceAll = require('./trace2');

const mqtt = require('mqtt')
const host = 'm1012864.cn-shenzhen.emqx.cloud'
const port = '11192'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`

const fs = require("fs");
const str = new Date();

fs.writeFile("./test_log.txt", "wwwww" + str, error => {
    if (error) return console.log("写入文件失败,原因是" + error.message);
    console.log("写入成功");
});


// connect options
const OPTIONS = {
    clientId,
    clean: true,
    connectTimeout: 4000,
    username: 'test',
    password: 'test',
    reconnectPeriod: 1000,
}
let connectUrl = `mqtt://${host}:${port}`
const topic = 'mqtt'
const client = mqtt.connect(connectUrl, OPTIONS)



client.sendData = function (data) {
    data.data = JSON.stringify(data.data);
    data = JSON.stringify(data) || ''
    client.publish(topic + '/client', data, { qos: 2, retain: false }, (error) => {
        if (error) {
            console.error(error)
        }
        // console.log('发送数据：', data);
    })
}


let index = 0
let interval;

console.log('正在连接...')
client.on('connect', () => {
    console.log('服务器已连接')
    interval = setInterval(() => {
        // let index = ~~(Math.random() * 10);
        let index = 0;

        client.sendData({type: 'robot_newPoint', data: traceAll[index]})
    }, 2000)
    client.subscribe([topic + '/server'], () => {
        console.log(`已订阅'${topic}'`)
    })
})



client.on('message', (topic, msg) => {
    msg = JSON.parse(msg);
    if (msg.type === 'baseControl') {
        msg = msg.data;
        if (msg === 'start') {
            index = 0;
            if (interval) {
                clearInterval(interval);
            }
            interval = setInterval(() => {
                if (traceAll[index]) {
                    client.sendData({type: 'robot_newPoint', data: traceAll[index]})
                }
                ++index;
                if (index === traceAll.length) {
                    index = 0;
                }
            }, 100)
        }
        if (msg === 'stop') {
            // index = 0;
            clearInterval(interval);
        }
        if (msg === 'goon') {
            interval = setInterval(() => {
                if (traceAll[index++]) {
                    client.sendData({type: 'robot_newPoint', data: traceAll[index++]})
                }
            }, 200)
        }
        if (msg === 'pause') {
            clearInterval(interval);
        }
    } else {
        if (msg.type === 'path') {
            client.sendData({type: 'robot_pathStatus', data: 200})
        }
    }
    
});

client.on('error', function (err) {
    console.log(err);
});
